import os
import sys
import tempfile
import subprocess
import requests

def download_remote_image(remote_url):
    """从远程URL下载图片到临时文件"""
    try:
        # 发送请求获取图片
        response = requests.get(remote_url, timeout=10)
        response.raise_for_status()  # 检查请求是否成功
        
        # 创建临时文件
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg')
        temp_file.write(response.content)
        temp_file.close()
        
        return temp_file.name
        
    except Exception as e:
        print(f"下载图片失败: {str(e)}")
        return None

def set_wallpaper(image_path):
    """使用CMD命令设置壁纸"""
    try:
        # 组合两个命令为一个命令字符串，使用;分隔
        command = (
            f'Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force; '
            f'$wallpaper = "{image_path}"; '
            f'Add-Type -TypeDefinition \'using System; using System.Runtime.InteropServices; public class Wallpaper {{ [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni); }}\'; '
            f'[Wallpaper]::SystemParametersInfo(20, 0, $wallpaper, 3)'
        )
        
        # 执行命令 - 通过powershell执行组合命令
        result = subprocess.run(
            ['powershell', '-Command', command],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        if result.returncode == 0:
            print("壁纸设置成功")
            return True
        else:
            print(f"设置壁纸失败: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"设置壁纸时出错: {str(e)}")
        return False

def main(remote_image_url):
    # 下载远程图片
    temp_image_path = download_remote_image(remote_image_url)
    if not temp_image_path:
        sys.exit(1)
    
    # 设置壁纸
    success = set_wallpaper(temp_image_path)
    
    # 清理临时文件
    try:
        os.unlink(temp_image_path)
    except Exception as e:
        print(f"清理临时文件失败: {str(e)}")
    
    return success

if __name__ == "__main__":
    # 示例：远程图片的URL，替换为实际的远程IP图片地址
    if len(sys.argv) > 1:
        remote_url = sys.argv[1]
    else:
        remote_url = input("请输入远程图片的URL: ")
    main(remote_url)
